import {
  authorize,
  wechatAuthorize
} from '@/api/modules/base'

import {
  getToken,
  setToken,
  removeToken,
  getConnect,
  setConnect,
  getSpread
} from '@/utils/auth'

const state = {
  token: getToken(),
  connect: getConnect(),
  spread: getSpread(),
  name: '',
  avatar: '',
  introduction: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_CONNECT: (state, data) => {
    state.connect = data
  }
}

const actions = {
  // base authorize
  system ({
    commit
  }, params) {
    return new Promise((resolve, reject) => {
      authorize(params).then(response => {
        const {
          data
        } = response
        console.log(data)
        commit('SET_TOKEN', data.access_token)
        setToken(data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // wechat authorize
  wechat ({
    commit
  }, params) {
    return new Promise((resolve, reject) => {
      wechatAuthorize(params).then(response => {
        const {
          data
        } = response
        if (data.token) {
          commit('SET_TOKEN', data.token)
          setToken(data.token)
        }
        if (data.connect) {
          commit('SET_CONNECT', data.connect)
          setConnect(data.connect)
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken ({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
